import { View, Text, Button, Image, RichText, ScrollView } from '@tarojs/components'
import { memo } from 'react'
import Taro from '@tarojs/taro'
import type { CommonEventFunction } from '@tarojs/components'
import { Checked } from "@taroify/icons"
import BtPopup from '../BtPopup'
import { useEffect, useState } from 'react'
import './index.scss'
import Login from '@/assets/images/home/party-love.png'
import utils from '@/utils'
import { useTokenStore } from '@/stores/useTokenStore'
import { AgreementType } from '@/api/types/enum'
import { ConfigProvider } from "@taroify/core";

type GetPhoneNumberEventDetail = {
    code?: string;
}

interface BtLoginProps {
    open: boolean,
    onClose?: (value: boolean) => void
    onSuccess?: () => void
}

function BtLogin({
    open,
    onClose,
    onSuccess
}: BtLoginProps) {
    const { openId } = useTokenStore()
    const [loginOpen, setLoginOpen] = useState(false);
    // 是否同意隐私协议
    const [isagreement, setAgreement] = useState(false);
    // 协议弹窗
    const [agreementOpen, setAgreementOpen] = useState(false);
    // 协议内容
    const [agreementContent, setAgreementContent] = useState('');
    // 隐私政策
    const [privacyContent, setPrivacyContent] = useState('');
    // 用户
    const [userContent, setuserContent] = useState('');
    // 协议类型-默认用户协议
    const [agreementTitle, setAgreementTitle] = useState('用户协议');
    useEffect(() => {
        // 判断当前页面是否在tabbar页面
        // const pages = Taro.getCurrentPages()
        // const isTabbarPage = pages[pages.length - 1].$taroPath?.includes('tabbar')
        if (open) {
            setLoginOpen(true)
            Taro.hideTabBar();
        } else {
            setLoginOpen(false);
            Taro.showTabBar();
        }
        console.log(loginOpen, '执行；额loginOpen')
    }, [open])

    // 手机号登录
    const getPhoneNumber: CommonEventFunction<GetPhoneNumberEventDetail> = async (e) => {
        let codeLoginOpenId = ''
        if (!openId) {
            const { code } = await utils.$taroApis.login()
            // 静默登录
            const data = await utils.$apis.codeLogin({ code, app: 'community' })
            codeLoginOpenId = data.meta.openId || data.meta.openid || '';
        }

        utils.$apis.login({ openId: openId || codeLoginOpenId, app: 'community', code: e.detail.code || '' }).then((res) => {
            Taro.setStorageSync('isLogin', false)
            Taro.showToast({
                title: '登录成功',
                icon: 'none'
            })
            onClose?.(false)
            onSuccess?.()
        }).catch((error) => {
            console.error('Login error:', error)
            Taro.showToast({
                title: '登录失败',
                icon: 'none'
            })
        })
    }
    // 没有同意协议提示
    const handleAgreement = () => {
        if (!isagreement) {
            Taro.showToast({
                title: '请先同意隐私协议',
                icon: 'none'
            })
        }
    }
    // 获取协议内容
    const getAgreementList = async (type: AgreementType, $event?: any) => {
        $event?.stopPropagation()
        setAgreementOpen(true)
        setAgreementTitle(type === AgreementType.SERVICE ? '用户协议' : '隐私政策')

        // 判断用户协议是否有值，有值则直接获取协议内容
        if (userContent && type === AgreementType.SERVICE) {
            setAgreementContent(userContent)
        } else if (privacyContent && type === AgreementType.PRIVACY) {
            setAgreementContent(privacyContent)
        } else {
            try {
                const res = await utils.$apis.getDictionariesList({ typeKey: 'agreement_type', status: true })
                res.forEach(item => {
                    if (item.key === type) {
                        getAgreementContent(item.id, type)
                    }
                })
            } catch (error) {
                console.error('Failed to get agreement list:', error)
            }
        }
    }

    // 获取协议内容
    const getAgreementContent = async (id: string, type: AgreementType) => {
        try {
            const res = await utils.$apis.getAgreementContent({ type: id })
            if (res) {
                let content = res.filter(item => item.type.key === type)[0].content;
                content = content.replace(/<img/g, '<img style="max-width: 100%; height: auto;"')
                if (type === AgreementType.SERVICE) {
                    setuserContent(content)
                } else {
                    setPrivacyContent(content)
                }
                setAgreementContent(content)
            }
        } catch (error) {
            console.error('Failed to get agreement content:', error)
        }
    }

    return (
        <>
            <ConfigProvider
                theme={{
                    zIndex: "9999999999",
                }}
            >
                <BtPopup open={loginOpen} onClose={onClose} rounded placement="bottom">
                    <View className="bt-login-popup">
                        <View className="bt-login-header">
                            <Image className="bt-login-logo" src={Login} />
                            <Text className="bt-login-title">南井沟小程序</Text>
                            <View className="bt-login-close" onClick={() => onClose?.(false)}>×</View>
                        </View>
                        <View className='bt-login-center'>
                            {!isagreement ?
                                <View className="bt-login-btn" onClick={handleAgreement}
                                >手机号快捷登录</View>
                                :
                                <Button className="bt-login-btn" open-type="getPhoneNumber" onGetPhoneNumber={getPhoneNumber}
                                >手机号快捷登录</Button>
                            }
                            {/* <View className="bt-login-btn other" onClick={() => { }}>其他登录方式</View> */}
                        </View>
                        <View className="bt-login-agree" onClick={() => setAgreement(!isagreement)}>
                            <View className='bt-login-agreebox '>
                                {
                                    !isagreement &&
                                    <Text className='bt-login-agreement'></Text>
                                }
                                {
                                    isagreement &&
                                    <Checked style={{ color: "#F20000" }} size={20} />
                                }
                            </View>
                            <Text>查看并同意</Text>
                            <Text className="bt-login-link" onClick={(e) => {
                                getAgreementList(AgreementType.SERVICE, e)
                            }}>《用户协议》</Text>
                            <Text>和</Text>
                            <Text className="bt-login-link" onClick={(e) => {
                                getAgreementList(AgreementType.PRIVACY, e)
                            }}>《隐私政策》</Text>
                        </View>
                    </View>
                </BtPopup>
            </ConfigProvider>

            {/* 协议 */}
            <BtPopup open={agreementOpen} onClose={() => setAgreementOpen(false)} rounded placement="bottom">
                <View className="bt-login-agreement-popup">
                    <View className="bt-login-agreement__header">
                        <Text className="bt-login-title">{agreementTitle}</Text>
                        <View className="bt-login-close" onClick={() => setAgreementOpen(false)}>×</View>
                    </View>

                    {/* 富文本 */}
                    <ScrollView
                        className='bt-login-agreement__content'
                        scroll-y
                    >
                        <RichText
                            nodes={agreementContent}
                            style={{
                                width: '100%',
                                wordWrap: 'break-word',
                                wordBreak: 'break-all'
                            }}
                        />
                    </ScrollView>
                </View>

            </BtPopup>
        </>
    )
}

export default memo(BtLogin)